package com.sk.weichat.ui.mucfile;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.entity.AbstractExpandableItem;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.sk.weichat.R;
import com.sk.weichat.adapter.TabFragmentPagerAdapter;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.ui.mucfile.bean.MucFileBean;
import com.sk.weichat.util.GetFileSizeUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.log.FileUtils;
import com.sk.weichat.view.LoadingDialog;
import com.sk.weichat.view.ScaleTransitionPagerTitleView;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

import static com.sk.weichat.ui.mucfile.bean.FileBean.FileBean_Key;

/**
 * MediaScannerConnection.scanFile(context, path, null, null);
 */
public class AddMucFileActivity2 extends BaseActivity {
    // private static final String[] CHANNELS = new String[]{"文档", "影音", "应用", "其他"};
    private static final String[] CHANNELS = new String[]{"文档", "影音", "相册", "应用", "其他"};
    private List<String> mDataList = Arrays.asList(CHANNELS);

    private TabFragmentPagerAdapter mExamplePagerAdapter;
    private ArrayList<Fragment> mFragmentList = new ArrayList<>();
    private ViewPager mViewPager;

    public static final String Action_Click = "AddMucFileActivity_ACTION_CLICK";

    MyReceiver receiver = new MyReceiver();

    static Map<String, Long> selectCaches = new HashMap<>();

    private TextView tvSize;
    private TextView tvSend;

    private String mRoomId;

    private boolean isSelectFile;

    public static final String SELECT_FILES = "AddMucFileActivity2_SELECT_FILES";
    //
    private static Map<String, Integer> typeIDs = new HashMap<>();

    static {
        typeIDs.put("png", 1);
        typeIDs.put("jpg", 1);
        typeIDs.put("jpeg", 1);
        typeIDs.put("mp3", 2);
        typeIDs.put("mp4", 3);
        typeIDs.put("avi", 3);
        typeIDs.put("ppt", 4);
        typeIDs.put("pptx", 4);
        typeIDs.put("xls", 5);
        typeIDs.put("xlsx", 5);
        typeIDs.put("doc", 6);
        typeIDs.put("docx", 6);
        typeIDs.put("docx", 6);
        typeIDs.put("rar", 7);
        typeIDs.put("zip", 7);
        typeIDs.put("txt", 8);
        typeIDs.put("pdf", 10);
        typeIDs.put("apk", 11);
    }

    private AtomicInteger index = new AtomicInteger(0);


    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_muc_file2);
        Intent intent = getIntent();
        if (intent != null) {
            mRoomId = intent.getStringExtra("roomId");
            //
            isSelectFile = intent.getBooleanExtra(SELECT_FILES, false);
        }

        initActionBar();
        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Action_Click);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(receiver, intentFilter);
        selectCaches.clear();
    }


    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(receiver);
        super.onDestroy();
    }

    private void initView() {
        loadingDialog = new LoadingDialog(mContext);
        tvSize = findViewById(R.id.tv_select_total_size);
        tvSend = findViewById(R.id.tv_send);
        tvSend.setEnabled(false);
        //发送文件
        RxView.clicks(tvSend).throttleFirst(10, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {


            @Override
            public void accept(Object o) throws Exception {
                if (isSelectFile) {
                    ArrayList<String> paths = new ArrayList<String>(selectCaches.keySet());
                    setResultForSelectFiles(paths);
                } else {
                    loadingDialog.show();
                    //
                    Iterator<Map.Entry<String, Long>> itar = selectCaches.entrySet().iterator();
                    int i = 0;
                    while (itar.hasNext()) {
                        i++;
                        Map.Entry<String, Long> entry = itar.next();
                        String path = entry.getKey();
                        upload(new File(path));
                    }
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

//        tvSend.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        //  mFragmentList.add(new MediaFileFragment());
        mFragmentList.add(new MediaFileFragment2());
        mFragmentList.add(new MediaVideoAndAudioFragment2());
        mFragmentList.add(new MediaImageFragment2());
        mFragmentList.add(new MediaApkFragment2());
        mFragmentList.add(new MediaOtherFragment2());

        mExamplePagerAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager = findViewById(R.id.view_pager);
        mViewPager.setAdapter(mExamplePagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(mExamplePagerAdapter);

        initMagicIndicator();
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    private void check() {
        if (selectCaches.size() == 0) {
            tvSend.setEnabled(false);
        } else {
            tvSend.setEnabled(true);
        }
    }

    private void initMagicIndicator() {
        MagicIndicator magicIndicator = findViewById(R.id.magic_indicator2);
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
                simplePagerTitleView.setLayoutParams(lp);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(AddMucFileActivity2.this, R.color.text_color_main));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(AddMucFileActivity2.this, R.color.text_color_main));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setLineHeight(UIUtil.dip2px(context, 8));
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setColors(Color.parseColor("#40c4ff"));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mViewPager);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        ((TextView) findViewById(R.id.tv_title_center)).setText(InternationalizationHelper.getString("JXMyFileVC_SelFile"));

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Action_Click)) {
                FileBean fileBean = intent.getParcelableExtra(FileBean_Key);
                String key = fileBean.getFile().getAbsolutePath();
                if (fileBean.isChecked()) {
                    selectCaches.put(key, fileBean.getFile().length());
                } else {
                    selectCaches.remove(key);
                }
                Iterator<Map.Entry<String, Long>> itar = selectCaches.entrySet().iterator();
                long total = 0;
                int i = 0;
                while (itar.hasNext()) {
                    i++;
                    Map.Entry<String, Long> entry = itar.next();
                    total += entry.getValue();
                }
                tvSize.setText("已选择 (" + GetFileSizeUtil.formatFileSize(total) + ")");
                tvSend.setText(selectCaches.size() == 0 ? "发送" : "发送 (" + i + ")");
                check();
            }
        }
    }

    private void upload(File file) {
        UploadingHelper.upfile(
                coreManager.getSelfStatus().accessToken,
                coreManager.getSelf().getUserId(),
                file,
                new UploadingHelper.OnUpFileListener() {

                    @Override
                    public void onSuccess(String url, String path) {
                        addFile(new File(path), url);
                    }

                    @Override
                    public void onFailure(String err, String path) {
                        ToastUtil.showToast(mContext, err);
                        // 不论成功失败，全走一遍就退出，
                        index.getAndIncrement();
                        setResultAndFinish();
                    }
                });
    }

    private void addFile(File file, final String url) {
        String suffix = "";
        try {
            suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
        } catch (Exception e) {
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("userId", coreManager.getSelf().getUserId());
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("size", file.length() + "");
        params.put("url", url);
        params.put("type", typeIDs.get(suffix) + "");
        params.put("name", file.getName());
        HttpUtils.get().url(coreManager.getConfig().UPLOAD_MUC_FILE_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        if (result == null) {
                            ToastUtil.showToast(mContext, getString(R.string.data_exception));
                            return;
                        }

                        ToastUtil.showToast(mContext, (InternationalizationHelper.getString("NUMBER") + " " + (index.get() + 1) + "/" + selectCaches.size() + " " +
                                InternationalizationHelper.getString("INDIVIDUAL") + InternationalizationHelper.getString("UPLOAD_SUCCESSFUL")));
                        // 不论成功失败，全走一遍就退出，
                        index.getAndIncrement();
                        setResultAndFinish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showToast(mContext, (getString(R.string.net_exception)));
                        // 不论成功失败，全走一遍就退出，
                        index.getAndIncrement();
                        setResultAndFinish();
                    }
                });
    }

    private void setResultAndFinish() {
        if (index.get() == selectCaches.size()) {
            loadingDialog.dismiss();
            Intent intent = new Intent();
            intent.putExtra("code", 200);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    }

    /**
     *
     */
    private void setResultForSelectFiles(ArrayList<String> filePaths) {
        Intent intent = new Intent();
        intent.putStringArrayListExtra(SELECT_FILES, filePaths);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }


    //判断是否超过最大限制
    public static boolean isAllowToSelect() {
        return selectCaches.size() < 9;
    }

}
